%% Author: kevin.jingqiu
%% Created: Jun 1, 2009
%% Description: First triangle number to have over 500 divisors
-module(p12).

%%
%% Exported Functions
%%
-export([solve/0]).

%%
%% API Functions
%%
solve() ->
    solve(5000).

solve(N) ->
    {N, T} = triangle_num(N),
    io:format("T[~p]=~p~n", [N,T]),
    NumDivisors = num_divisors(T, 2, 1),
    case (NumDivisors-500) of
        Pos when Pos >= 0 ->
            {N, T};
        _ ->
            solve(N+1)
    end.

num_divisors(T, Cur, NumDivisors) ->
    case Cur > math:sqrt(T) of
        true ->
            NumDivisors + 1;
        _ ->

        case divide(T, Cur) of
            false ->
                num_divisors(T, Cur+1, NumDivisors);
            {Num, Num} ->
                num_divisors(T, Cur+1, NumDivisors+1);
            {_Num, _Congjugal} ->
                num_divisors(T, Cur+1, NumDivisors+2)
        end
    end.

divide(N, Divisor) ->
    case N rem Divisor of
        0 -> {Divisor, N div Divisor};
        _ -> false
    end.


triangle_num(N) ->
    {N, ((1+N) * N) div 2}.

